/*
 * @Author: 肖思汗 
 * @Date: 2025-06-02 14:52:57 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-26 16:17:53
 */

import Taro from "@tarojs/taro";
import { makeAutoObservable } from "mobx";
// import userApi from "./userApi";
class UserStore {
    constructor() {
        makeAutoObservable(this, {}, { deep: false });
        this.login();
    }

    // 登录状态
    isLogin = false;
    setIsLogin(isLogin: boolean) {
        this.isLogin = isLogin;
    }
    isloading = false;
    setIsloading(isloading: boolean) {
        this.isloading = isloading;
    }
    // 登录
    async login() {
        if (!this.isLogin && !this.isloading) {
            this.isloading = true;
            // const token = Taro.getStorageSync('token');
            // if (token) {
            //     const { default: userInfoApi } = await import("src/subPages/UserInfo/userInfoApi");
            //     const userInfoRes = await userInfoApi.getCurrentUser();
            //     if (userInfoRes.code === 200) {
            //         this.isloading = false;
            //         userStore.setIsLogin(true);
            //         return;
            //     }
            // }
            await Taro.login({
                success: async (res) => {
                    if (res.code) {
                        console.log("res.code", res.code);
                        const { default: userApi } = await import("./userApi");
                        const result = await userApi.wxLogin(res.code);
                        if (result.code == 200) {
                            Taro.setStorageSync('token', result.msg);
                            // console.log('code:', res.code, result.msg);
                            userStore.setIsLogin(true);
                        }
                    } else {
                        console.error(res.errMsg);
                    }
                },
            });
            this.isloading = false;
        }

        while (this.isLogin === false) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }


    }

    // 等待登录成功
    async awaitLogined() {
        while (this.isLogin === false) {
            await new Promise(resolve => setTimeout(resolve, 100));
        }
    }

    waitPay = 0; // 待支付订单数量
    waitDelivery = 0; // 待发货订单数量
    delivered = 0; // 已发货订单数量
    received = 0; // 已收货订单数量
    closed = 0; // 已关闭订单数量
    // 查询用户订单状态数量
    async getOrderStatusStatistics() {
        await this.awaitLogined();
        const { default: userApi } = await import("./userApi");
        userApi.getOrderStatusStatistics().then(res => {
            if (res.code == 200) {
                this.waitPay = res.data.waitPay;
                this.waitDelivery = res.data.waitDelivery;
                this.delivered = res.data.delivered;
                this.received = res.data.received;
                this.closed = res.data.closed;
            }
        })
    }


}

const userStore = new UserStore();

export default userStore;